// 引用qs模块处理axios发送的数据
import qs from 'qs';
// 配置API接口地址
var root = '';
// 引用axios
var axios = require('axios');
// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

// 参数过滤函数
function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key];
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim();
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key]);
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key]);
    }
  }
  return o;
}

axios.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

function apiAxios (method, url, params, success, failure) {
  if (params) {
    params = filterNull(params);
  }
  axios({
    method: method,
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    baseURL: root,
    withCredentials: true
  })
    .then(function (res) {
      if (res) {
        if (success) {
          if (res.data.code == '03') {
            let location = window.location.href.split('#');
            window.location.href = location[0];
            sessionStorage.setItem('login', 'true');
          }
          success(res.data);
        }
      } else {
        if (failure) {
          failure(res.data);
        } else {
          window.alert('error: ' + JSON.stringify(res.data));
        }
      }
    })
    .catch(function (err) {
      if (err) {
        console.log(err);
        window.alert('网络异常，或服务不可用');
      }
    });
}

// 返回在vue模板中的调用接口
export default {
  get: function (url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure);
  },
  post: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure);
  },
  put: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure);
  },
  delete: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure);
  }
};
